<?php

namespace app\common\model;


    /**
      * 订购模型
      *@author NetLife <40150501@qq.com>
    **/
class Books extends Base{

    /**
      * deal_cartoon_buy [图书购买流程]
      *
      * @param type $uid         [用户id]
      * @param type $cartoonid   [小说、漫画ID]
      * @param type $cartoonname [小说、漫画名称]
      * @param type $volumeid    [小说、漫画章节ID]
      * @param type $volumename  [小说、漫画章节名称]
      * @param type $isvip       [是否VIP章节]
      * @param type $saleprice   [售价]
      * @param type $model       [模型1:小说 2：漫画]
      * @param type $autobuy       [是否查询自动购买过 1：查询 0：不查询]
	  * @param type $source       [来源 1:CPS平台 2：APP]

      * @return type
    **/
	public function deal_cartoon_buy($uid,$cartoonid,$cartoonname,$volumeid,$volumename,$isvip,$saleprice,$model,$autobuy=1,$source=1){

		//是否VIP章节
		if($isvip==0){
			return true;
		}

		$member = db('member')->where('uid',$uid)->find();
		
		//月/季/年会员  在时间内
		if($member['is_vip']>0 && $member['vip_enddate'] >time()){
			//订阅记录
			$this->subscription($uid,$cartoonid,$cartoonname,$volumeid,$volumename,$model,$saleprice,5,$source);
			return true;
		}

		if($autobuy){
			$info  = db('autobuy')->where(array('user_id'=>$uid,'cartoon_id'=>$cartoonid,'model'=>$model))->find();
			
			//不存在自动购买
			if(empty($info)){
				return false;
			}
		}

		//是否已经买过了
		$is_order =  db('subscription')->where(array('uid'=>$uid,'articleid'=>$cartoonid,'chapterid'=>$volumeid,'model'=>$model))->select();

		if($is_order){
			return true;
		}

		//金币数量是否够用
		if( ($member['egold']+$member['zb']+$member['sign_score'])>=$saleprice){
			//先消费赠币的情况下
			
			if(($member['zb']+$member['sign_score'])>=$saleprice){

				$this->signbuy($uid,$saleprice);

				//签到赠币支付
				if($member['sign_score']>$saleprice){
					db('member')->where('uid',$uid)->setDec('sign_score',$saleprice);
				}else{
					//修改签到赠币支付
					db('member')->where('uid',$uid)->setField('sign_score', '0');
					//还需要的书币
					$need = $saleprice-$member['sign_score'];
					db('member')->where('uid',$uid)->setDec('zb',$need);
				}
				$buytype = 3;
				//所有消费日志
				$this->logs($uid,3,"订阅消费赠币",0,$saleprice);
			}else{
				db('member')->where('uid',$uid)->update(['sign_score' => 0,'zb'=>0]);
				$need = $saleprice-$member['sign_score']-$member['zb'];
				//修改用户金币
				if($need>0){
					db('member')->where('uid',$uid)->setDec('egold',$need);
				}else{
					db('member')->where('uid',$uid)->setDec('egold',$saleprice);
				}
				$buytype = 2;
				//所有消费日志
				$this->logs($uid,3,"订阅消费",0,$saleprice);
			}
			
			/**
			//先消费阅读的情况下
			if($member['egold'] < $saleprice){
				if($member['egold']>0){
					//修改用户金币
					db('member')->where('uid',$uid)->setField('egold', '0');
				}
				//还需要的赠币
				$need = $saleprice-$member['egold'];
				db('member')->where('uid',$uid)->setDec('zb',$need);
				//消费类别 1:打赏消费 2:阅读币消费 3:赠币消费
				$buytype = 3;
			}else{
				//修改用户金币
				db('member')->where('uid',$uid)->setDec('egold',$saleprice);
				$buytype = 2;
				//所有消费日志
				$this->logs($uid,3,"订阅消费",0,$saleprice);
			}
			**/
			//订阅记录
			$this->subscription($uid,$cartoonid,$cartoonname,$volumeid,$volumename,$model,$saleprice,$buytype,$source);
			//消费记录
			$this->osalelog($uid,$cartoonid,$cartoonname,$volumeid,$volumename,$saleprice,1,$model,$buytype,$source);
			return true;
		}
		return false;
	}
	/******签到赠币使用*****/
	public function signbuy($uid,$saleprice) {
		$score = db('member_point')->where("uid = $uid and expire_time>".strtotime(date('Y-m-d')))->order('expire_time ASC')->select();
		if($score){
			$sumPoint = 0;
			//保存要更新的recordId
			$recordIds = array();
			//目标记录
			$targetRecord = array();
			foreach ($score as $k=>$v){
				//累加，直到值大于等于$saleprice
				$sumPoint += $v['egold'];
				if($sumPoint>= $saleprice){
					$targetRecord =$v;
					break;
				}
				//记录相应的id值
				$recordIds[]=$v['id'];
				
			}
			if($sumPoint < $saleprice) {
				//当前积分不足以消耗
				db('member_point')->where("uid = $uid ")->delete();
			}elseif($sumPoint == $saleprice) {
				//加上最后一条记录的值后，总额刚好等于使用额度
				$recordIds[]=$targetRecord['id'];
			} else {
				$recordIds[]=$targetRecord['id'];
				// 加上最后一条记录的值后，总额刚好大于使用额度，此时需要将最后一条记录拆成两条记录
				$leftPoint = $sumPoint - $saleprice;
				$usePoint = $targetRecord['egold']-$leftPoint;
				
				//添加一条记录
				$point=array(
					'uid'=>$targetRecord['uid'],
					'egold'=>$leftPoint,
					'add_time'=>$targetRecord['add_time'],
					'expire_time'=>$targetRecord['expire_time']
				);
				db('member_point')->insert($point);
				//修改最后一条记录的积分值
				db('member_point')->where('id='.$targetRecord['id'])->update(['egold' =>$usePoint]);
				
			}
			
			//按id删除记录
			if($recordIds){
				db('member_point')->delete(array_unique($recordIds));
			}
			//处理积分总额
			/*
			$total = db('member_point')->where("uid = $uid and expire_time>".strtotime(date('Y-m-d')))->sum('egold');
			$total = $total>0?$total:0;
			db('member')->where("uid = $uid")->setField('sign_score', $total);
			*/
		}
	}

	/*****全本购买****/
	public function allbookbuy($uid,$cartoonid,$cartoonname,$saleprice,$model,$source=1) {	
		$member = db('member')->where('uid',$uid)->find();
		
		//金币数量是否够用
		if($saleprice < ($member['egold']+$member['zb']+$member['sign_score'])){
			
			if($member['egold'] < $saleprice){
				if($member['egold']>0){
					//修改用户金币
					db('member')->where('uid',$uid)->setField('egold', '0');
				}
				//还需要的赠币
				$need = $saleprice-$member['egold'];
				db('member')->where('uid',$uid)->setDec('zb',$need);
				//消费类别 1:打赏消费 2:阅读币消费 3:赠币消费
				$buytype = 43;
			}else{
				//所有消费日志
				$this->logs($uid,3,"全本购买消费",0,$saleprice);

				//修改用户金币
			    db('member')->where('uid',$uid)->setDec('egold',$saleprice);
				$buytype = 42;
			}
			
			//订阅记录
			$this->subscription($uid,$cartoonid,$cartoonname,'','',1,$saleprice,4,1);
			//消费记录
			$this->osalelog($uid,$cartoonid,$cartoonname,'','',$saleprice,1,1,4,1);
			return true;
		}
		return false;
	}
	//扣币过程
	public function buyprocess($uid,$member,$saleprice) {
		if(($member['zb']+$member['sign_score'])>$saleprice){
			//签到赠币支付
			if($member['sign_score']>$saleprice){
				db('member')->where('uid',$uid)->setDec('sign_score',$saleprice);
			}else{
				//修改签到赠币支付
				db('member')->where('uid',$uid)->setField('sign_score', '0');
				//还需要的书币
				$need = $saleprice-$member['sign_score'];
				db('member')->where('uid',$uid)->setDec('zb',$need);
			}
			$buytype = 3;
		}else{
			db('member')->where('uid',$uid)->update(['sign_score' => 0,'zb'=>0]);
			$need = $saleprice-$member['sign_score']-$member['zb'];
			//修改用户金币
			if($need>0){
				db('member')->where('uid',$uid)->setDec('egold',$need);
			}else{
				db('member')->where('uid',$uid)->setDec('egold',$saleprice);
			}
			$buytype = 2;
		}
		return $buytype;
	}
	
    /**
      * subscription [订阅记录]
      *
      * @param type $uid         [用户ID]
	  * @param type $cartoonid   [小说、漫画ID]
      * @param type $cartoonname [小说、漫画名称]
      * @param type $volumeid    [小说、漫画章节ID]
      * @param type $volumename  [小说、漫画章节名称]
       * @param type $model      [模型1:小说 2：漫画]
      * @param type $saleprice   [售价]
      * @param type $buytype     [消费类别 1:打赏消费 2:阅读币消费 3:赠币消费 4:全本购买]
      *
      * @return type
    **/
	public function subscription($uid,$cartoonid,$cartoonname,$volumeid=0,$volumename='',$model=1,$saleprice=0,$buytype=1,$source=1) {
		//订阅记录

		//$this->subscription($uid,$cartoonid,$cartoonname,'','',1,$saleprice,4,1);

		$subscription = array(
			'uid' =>$uid,
			'username' =>get_nickname($uid),
			'articleid' =>$cartoonid,
			'articlename' =>$cartoonname,
			'chapterid' =>$volumeid,
			'chaptername' =>$volumename,
			'model' =>$model,
			'price' =>$saleprice,
			'buytype' =>$buytype,
			'sourceid' =>$source,
			'create_time' =>time()
		);
		//var_dump($subscription);exit();
		db('subscription')->insert($subscription);

		if($buytype==3){//阅读币消费才统计
			$report = model('Report');
			//订阅日统计
			$report->actday(1,$cartoonid,date('Y-m-d'),$saleprice);
			//订阅月统计
			$report->actmonth(1,$cartoonid,date('Y-m'),$saleprice);
		}
	}

	/***章节是否购买***/
	public function is_buy($model,$uid,$cartoonid,$volumeid) {

		$member = db('member')->where('uid',$uid)->find();
		
		//月/季/年会员  在时间内
		if($member['is_vip']>0 && $member['vip_enddate'] >time()){
			return true;
		}
		
		//限时免费
		$free = db('limitedfree')->where('enddate >'.time())->order('create_time DESC')->limit(1)->find();
		if($free){
			$limitedfree = explode(",",$free['articleid']);
			if(in_array($cartoonid,$limitedfree)){
				return true;
			}
		}
		
		//是不是整本购买过了
		$allbook =  db('subscription')->where(array('uid'=>$uid,'articleid'=>$cartoonid,'model'=>$model,'buytype'=>4))->value('id');
		
		if($allbook){
			return true;
		}
		
		//是否已经买过了
		$order =  db('subscription')->where(array('uid'=>$uid,'articleid'=>$cartoonid,'chapterid'=>$volumeid,'model'=>$model))->value('id');
		
		if($order){
			return true;
		}

		return false;
	}

	/***批量购买*****/

	public function batchbuy($uid,$articleid,$chapterid) {
		//获取小说信息
		$article = db('novel')->where('id='.$articleid)->cache(true)->field('id,title')->find();
		if(strpos($chapterid,',') !==false){
			$chapterid = explode(',',$chapterid);
			foreach($chapterid as $v){
				$chapter = db('chapter')->where('id='.$v)->cache(true,3600)->field('id,chaptername,isvip,saleprice')->find();
				if($chapter['isvip']==1){
					//修改用户金币
					db('member')->where('uid',$uid)->setDec('egold',$chapter['saleprice']);
					$buytype = 2;
					//增加订阅记录
					$this->subscription($uid,$article['id'],$article['title'],$chapter['id'],$chapter['chaptername'],1,$chapter['saleprice'],2,2);
					//消费记录
					$this->osalelog($uid,$article['id'],$article['title'],$chapter['id'],$chapter['chaptername'],$chapter['saleprice'],1,1,2,2);
				}
			}
		}else{
			$chapter = db('chapter')->where('id='.$chapterid)->cache(true,3600)->field('id,chaptername,isvip,saleprice')->find();
			if($chapter['isvip']==1){
				//修改用户金币
				db('member')->where('uid',$uid)->setDec('egold',$chapter['saleprice']);
				$buytype = 2;
				//增加订阅记录
				$this->subscription($uid,$article['id'],$article['title'],$chapter['id'],$chapter['chaptername'],1,$chapter['saleprice'],2,2);
				//消费记录
				$this->osalelog($uid,$article['id'],$article['title'],$chapter['id'],$chapter['chaptername'],$chapter['saleprice'],1,1,2,2);
			}
		
		}
		return true;
	}

	//消费记录
	public function osalelog($uid,$cartoonid,$cartoonname,$volumeid,$volumename,$saleprice,$num=1,$model=2,$buytype,$source=1) {
		$osale = [
			'uid' =>$uid,
			'username' =>get_nickname($uid),
			'actname'=>$buytype,
			'articleid' =>$cartoonid,
			'articlename' =>$cartoonname,
			'chapterid' =>$volumeid,
			'chaptername' =>$volumename,
			'saleprice' =>$saleprice,
			'num' =>$num,
			'model' =>$model,
			'sourceid' =>$source,
			'create_time' =>time()
		];
		db('osale')->insert($osale);
	}

	//所有消费日志
	public function logs($uid,$type,$title,$money,$egold) {
		$log['user_id'] =$uid;
		$log['type'] =$type;
		$log['title'] =$title;
		$log['money'] =$money;
		$log['shubi'] ="-".$egold;
		$log['created_at'] =time();
		db('chongzhi_log')->insert($log);
	}
	//自定义价格
	public function diyprice($bookid,$chapter,$host='') {
		if(empty($host)){
			$host = explode('.',$_SERVER['HTTP_HOST']);
		}else{
			$host = explode('.',$host);
		}
		
		if(strpos($host[0],'t') !==false){
			$uid = split_host($host[0]);
			$wxmpid= split_host($host[0],2);
			$diyprice = db('diyprice')->where("uid",$uid)->where("wxmpid",$wxmpid)->where("articleid",$bookid)->find();
			
			if(config('pricetype')==1){//按章收费
				if($diyprice&&!empty($diyprice["saleprice"])){
					return $diyprice["saleprice"];
				}else{
					return false;
				}
			}else{
				//按字收费
				if($diyprice&&!empty($diyprice["wordsperegold"])){
					return  round($chapter['size']/1000*$diyprice["wordsperegold"]);
				}else{
					return false;
				}
			}
		}
	}

}